package query

import (
	"context"

	v1 "code.byted.org/bytertc/whiteboard_server/biz/api/pb/v1"
	"code.byted.org/bytertc/whiteboard_server/biz/service/command"
	"code.byted.org/bytertc/whiteboard_server/biz/service/command/base"
)

func NewSnapshotCommand(ctx context.Context, cmd *base.Command, id, pageId string, boardId int32, objects []string) command.Command {
	return &snapshotCommand{
		Command: *cmd,
		id:      id,
		boardId: boardId,
		pageId:  pageId,
		objects: objects,
	}
}

type snapshotCommand struct {
	base.Command
	id      string
	boardId int32
	pageId  string
	objects []string
}

func (s *snapshotCommand) Execute(ctx context.Context) []command.Result {
	elements, err := s.Repo.GetElements(ctx, s, s.objects)
	resp := &v1.GetShapeSnapshotResponse{
		Id:      s.id,
		BoardId: s.GetBoardId(),
		PageId:  s.GetPageId(),
		Version: 1,
		ObjList: make([]*v1.Element, 0, len(elements)),
	}
	res := &base.Result{
		Msg:         resp,
		IsBroadcast: false,
		CommandType: v1.Command_kGetShapeSnapshot,
		Error:       err,
	}
	if err != nil {
		res.Error = err
		return []command.Result{res}
	}

	for _, ele := range elements {
		if !ele.GetInitStatus() {
			continue
		}
		resp.ObjList = append(resp.ObjList, ele.ToProto())
	}
	return []command.Result{res}
}

func (s *snapshotCommand) GetBoardId() int32 {
	return s.boardId
}

func (s *snapshotCommand) GetPageId() string {
	return s.pageId
}
